package com.lzj.interceptor;

import com.lzj.entity.Employee;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * <p>
 *
 * </p>
 *
 * @autor:lzj
 * @date:2022/2/27
 */
public class PermissInterceptor implements HandlerInterceptor {
    AntPathMatcher pathMatcher =new AntPathMatcher();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if("/".equals(requestURI)||"/doLogin".equals(requestURI)||"/doReg".equals(requestURI)||"/register".equals(requestURI)){
            return true;
        }
        HttpSession session = request.getSession(true);
        Employee currentuser = (Employee) session.getAttribute("currentuser");
        if(pathMatcher.match("/admin/**",requestURI)){//判断是否是管理员
            if (currentuser!=null){
                if(currentuser.getRole().equals("2")){
                    return true;
                }else{
                    response.getWriter().write("forbidden");
                    return false;
                }
            }
        }else{
            if(currentuser!=null){
                return true;
            }
            response.sendRedirect("/");
            return false;
        }
        response.sendRedirect("/");
        return false;
    }
}
